﻿Public Class SecurityMenuControl

    Private WithEvents _businessData As MetaQuery
    Public Property QueryName() As String
    Public Property KeyFieldName() As String
    Public Property ParentFieldName() As String
    Public Property GridActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property DefaultActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property TreeContextMenu As TreeListMenu
    Public Property PanelName() As String

    Private aGridControl As GridExtPL
    Private pl As SystemBoxSDK.PL.MetaSDK.MetaControlProps_PL = New SystemBoxSDK.PL.MetaSDK.MetaControlProps_PL("SecurityControlProps")

    Private Sub ContextMenuCollapseAll(ByVal sender As Object, ByVal e As EventArgs)
        TreeList1.CollapseAll()
    End Sub

    Private Sub ContextMenuExpandAll(ByVal sender As Object, ByVal e As EventArgs)
        TreeList1.ExpandAll()
    End Sub

    Private Sub ContextMenuReload(ByVal sender As Object, ByVal e As EventArgs)
        ReloadTree()
    End Sub
    Public Sub ReloadTree()
        Me.Cursor = Cursors.WaitCursor
        TreeList1.DataSource = Nothing
        InitData()
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String
        Try
            filename = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), TreeList1.Tag.ToString)
            Using aFile As New System.Windows.Forms.SaveFileDialog
                aFile.DefaultExt = "xls"
                aFile.FileName = filename
                aFile.AutoUpgradeEnabled = True
                If aFile.ShowDialog() = DialogResult.OK Then

                    TreeList1.OptionsPrint.AutoWidth = False
                    TreeList1.OptionsPrint.PrintAllNodes = True
                    TreeList1.OptionsPrint.PrintFilledTreeIndent = True
                    TreeList1.OptionsPrint.PrintTreeButtons = False
                    TreeList1.ExportToXls(aFile.FileName)

                    MessageWindow.ShowMessage(String.Format("Export To Excel Succesfull.{0}{0}Your Filename is: {1}", vbCrLf, aFile.FileName), MsgBoxStyle.Information)

                End If
            End Using

        Catch ex As Exception
            Throw ex
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub InitActionOption()
        Dim act As CommonExt.Base.ActionOption
        GridActionOptionList = New CommonExt.Base.ActionOptionList()
        DefaultActionOptionList = New CommonExt.Base.ActionOptionList()
        act = New ActionOption("TreeOption", "ACT_00149", "Reload Data", AddressOf ContextMenuReload, True, True)
        DefaultActionOptionList.Add(act)
        act = New ActionOption("TreeOption", "ACT_00150", "Export to Excel", AddressOf ContextMenuExportToExcel, True, True)
        DefaultActionOptionList.Add(act)
        act = New ActionOption("TreeOption2", "ACT_00151", "Collaps All", AddressOf ContextMenuCollapseAll, True, True)
        DefaultActionOptionList.Add(act)
        act = New ActionOption("TreeOption2", "ACT_00152", "Expand All", AddressOf ContextMenuExpandAll, True, True)
        DefaultActionOptionList.Add(act)
    End Sub
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        TreeList1.ForceInitialize()
        InitActionOption()
    End Sub

    Public Sub New(ByVal aQueryname As String)
        Me.New()
        QueryName = aQueryname
    End Sub

    Public Sub InitData()
        'Dim hideCol As Boolean
        Dim colname As String
        Dim Column As DevExpress.XtraTreeList.Columns.TreeListColumn
        Dim colVisible As Boolean

        TreeList1.BeginUpdate()
        TreeList1.Tag = QueryName
        _businessData = MetaQuery.GetMetaQueryByName(QueryName)
        _businessData.FillResultQuery()
        TreeList1.KeyFieldName = KeyFieldName
        TreeList1.ParentFieldName = ParentFieldName
        TreeList1.DataSource = _businessData.ResultQuery
        TreeList1.ExpandAll()
        TreeList1.OptionsBehavior.EnableFiltering = True

        'Dim fc12 As FilterCondition = New FilterCondition(FilterConditionEnum.Contains, colLOCATION, "San Francisco")

        ' TreeList1.RefreshDataSource()
        ' TreeList1.PopulateColumns(
        ' TreeList1.BestFitColumns()
        TreeList1.Columns.Clear()
        For Each row As DataRow In _businessData.MetaColumns.Rows
            colname = row("ColumnName").ToString
            'hideCol = False
            'If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
            '    If colname.EndsWith("_ALT") Then
            '        hideCol = True
            '    End If
            'Else
            '    If colname.EndsWith("_PRM") Then
            '        hideCol = True
            '    End If
            'End If
            'If hideCol = False Then
            colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
            Column = TreeList1.Columns.AddField(colname)
            Column.VisibleIndex = CInt(row("pOrder"))
            Column.Caption = row("pCaption").ToString
            Column.Visible = colVisible
            Column.Width = CInt(row("pWidth"))
            'Column.ToolTip = row("pToolTip").ToString

            Column.AllowIncrementalSearch = True
            Column.OptionsColumn.AllowEdit = False
            Column.OptionsColumn.ShowInCustomizationForm = True

            Column.Format.FormatType = GetFormatType(row)
            Column.Format.FormatString = row("pNumberFormat").ToString

            'formatType = GetFormatType(row)
            '
            'Column.DisplayFormat.FormatType = formatType
            'Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
            'End If
        Next
        TreeList1.EndUpdate()
    End Sub

    Private Sub DoShowMainViewMenu(ByVal hi As TreeListHitInfo)
        Dim item As DXMenuItem
        Dim grpName As String = String.Empty
        Dim lvl As Integer
        '
        TreeContextMenu = New DevExpress.XtraTreeList.Menu.TreeListMenu(TreeList1)
        If GridActionOptionList IsNot Nothing Then

            lvl = TreeList1.FocusedNode.Level

            If lvl = 0 Then
                For Each action As CommonExt.Base.ActionOption In DefaultActionOptionList
                    item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                    item.Enabled = action.Enabled
                    'Add new Group Separator when Group Name change
                    If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                        item.BeginGroup = True
                    End If
                    grpName = action.OptionGroup
                    TreeContextMenu.Items.Add(item)
                Next
            End If
            ''Add Action Option that need the grid DataRow
            'For Each action As CommonExt.Base.ActionOption In Me.GridActionOptionList
            '    item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
            '    item.Tag = TreeList1.FocusedNode()
            '    item.Enabled = action.Enabled
            '    'item.Image = action.OptionIcon
            '    If item.Tag Is Nothing Then
            '        item.Enabled = False
            '    End If
            '    'Add new Group Separator when Group Name change
            '    If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
            '        item.BeginGroup = True
            '    End If
            '    grpName = action.OptionGroup
            '    If String.IsNullOrEmpty(action.QueryName) OrElse action.QueryName = GridView1.Tag.ToString Then
            '        ContextMenu.Items.Add(item)
            '    End If
            'Next
            'Display Menu
            TreeContextMenu.Show(hi.MousePoint)
        End If
    End Sub
    Private Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function

    Private Sub SecurityMenuControl_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TreeList1.KeyUp
        If e.Control And e.Alt And e.KeyCode = Keys.Q Then
            Dim message As String
            message = String.Concat("MetaQuery: ", Me.QueryName, vbCrLf)
            MessageWindow.ShowMessage(message, MsgBoxStyle.Information)
        End If
    End Sub



    Private Sub TreeListExt_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        InitData()
    End Sub

    Private Sub TreeList1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TreeList1.MouseClick
        Dim hitInfo As TreeListHitInfo = TreeList1.CalcHitInfo(e.Location)
        Dim node As TreeListNode = TreeList1.FocusedNode
        If e.Button = MouseButtons.Right Then
            DoShowMainViewMenu(hitInfo)
        End If
        If e.Button = MouseButtons.Left Then
            'DataRow = TreeList1.g.GetFocusedDataRow()
            'Dim imExplorer As IMExplorer = New IMExplorer(DataRow)
            If hitInfo.HitInfoType = HitInfoType.Cell Then
                Me.Cursor = Cursors.WaitCursor
                PopulateDetailSection(node)
                Me.Cursor = Cursors.Default
            End If
        End If
    End Sub

    Private Sub PopulateDetailSection(ByVal node As TreeListNode)

        Dim guidParent As Guid = Nothing
        Dim guidEnfant As Guid = DirectCast(node.GetValue(Me.KeyFieldName), Guid)

        If node.Level > 0 Then
            guidParent = DirectCast(node.GetValue(Me.ParentFieldName), Guid)
        End If

        pl.SQLWhere = String.Format("ControlID_FK = '{0}'", guidEnfant)
        pl.ControlID_FK = guidEnfant

        'BestPractice: To manage memory
        If aGridControl IsNot Nothing Then
            aGridControl.Dispose()
            aGridControl = Nothing
        End If
        aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = pl, .Name = "SecurityMenuForm"}

        Dim action As ActionOption
        action = New ActionOption("SubjectMenu0", "ACT_00187", "Export Subject Security to " + AppManager.ExportToMasterDB, AddressOf ExportToMaster, True, True)
        aGridControl.GridActionOptionList.Add(action)
        action = New ActionOption("SubjectMenu", "ACT_00153", "Export Subject Security", AddressOf Export, True, True)
        aGridControl.GridActionOptionList.Add(action)
        action = New ActionOption("SubjectMenu", "ACT_00154", "Import Subject Security", AddressOf Import, True, True)
        aGridControl.GridActionOptionList.Add(action)

        AddHandler aGridControl.InitNewMasterRow, AddressOf NewMasterRow
        aGridControl.SecureGrid = True

        '
        'On trouve la form pour effacer les controle dedans et ensuite remettre le bon.
        'Comme ca on change le Detail selon la ligne dans L'explorer
        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Text = node.Item("ControlName").ToString()
                aFrm.Show()
                aFrm.Focus()
            End If
            aFrm.Refresh()
        Next
    End Sub

    Private Sub NewMasterRow(ByVal sender As Object, ByVal e As InitNewRowEventArgs)
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()
        'Using mc As PLSDK.PL.MetaSDK.MetaControlProps_PL = New PLSDK.PL.MetaSDK.MetaControlProps_PL()
        pl.NewRecord(row)
        'End Using
    End Sub

    Private Sub Export(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim propID As Guid
        Using aFile As New System.Windows.Forms.SaveFileDialog
            aFile.DefaultExt = "xml"
            aFile.FileName = "MetaControlProps_" + aDataRow("ControlPropID").ToString
            If aFile.ShowDialog() = DialogResult.OK Then
                propID = New Guid(aDataRow("ControlPropID").ToString)
                If SystemBoxSDK.PL.MetaSDK.MetaControlProps_PL.ExportMetaControlProps(aFile.FileName, propID) Then
                    MessageWindow.ShowMessage("Export Subject Security successful", MsgBoxStyle.Information)
                End If
            End If
        End Using
    End Sub

    Private Sub ExportToMaster(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim isValid As Boolean = False
        Dim listOfDataRows As List(Of DataRow) = CType(CType(sender, DXMenuItem).Tag, List(Of DataRow))

        For Each aDataRow As DataRow In listOfDataRows
            Dim propID As Guid = New Guid(aDataRow("ControlPropID").ToString)
            Try
                isValid = SystemBoxSDK.PL.MetaSDK.MetaControlProps_PL.ExportMetaControlPropsToMaster(propID)
            Catch ex As Exception
                Throw ex
            End Try
        Next
        If isValid Then
            MessageWindow.ShowMessage("Export Subject Security successful", MsgBoxStyle.Information)
        End If
    End Sub

    Private Sub Import(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim saved As Boolean
        Using aFile As New System.Windows.Forms.OpenFileDialog
            aFile.FileName = "*.xml"
            aFile.DefaultExt = "xml"
            aFile.Multiselect = True
            If aFile.ShowDialog() = DialogResult.OK Then
                For Each file As String In aFile.FileNames
                    saved = SystemBoxSDK.PL.MetaSDK.MetaControlProps_PL.ImportMetaControlProps(file)
                Next
                If saved Then
                    MessageWindow.ShowMessage("Import Subject Security successful", MsgBoxStyle.Information)
                End If
            End If
        End Using
    End Sub

End Class

